package com.xb.statement;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;

public class StatementDemo {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入用户名：");
        String user = scanner.nextLine();
        System.out.print("请输入密码：");
        String password = scanner.nextLine();
//SELECT user,password FROM user_table WHERE user = '1' or ' AND password = '=1 or '1' = '1'
        //请输入用户名：1' or
        //请输入密码：=1 or '1' = '1
        //Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'.
        // The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
        //登录成功
        String sql = "SELECT user,password FROM user_table WHERE user = '"+ user +"' AND password = '"+ password +"'";
		User returnUser = get(sql,User.class);
		if(returnUser != null){
			System.out.println("登录成功");
		}else{
			System.out.println("用户名不存在或密码错误");
		}
    }

    // 使用Statement实现对数据表的查询操作
	public static  <T> T get(String sql,Class<T> cls) throws SQLException {
		T t = null;
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			InputStream resourceAsStream = StatementDemo.class.getClassLoader().getResourceAsStream("mysqlConnectInfo.properties");
			Properties properties = new Properties();
			properties.load(resourceAsStream);
			Class.forName(properties.getProperty("driver"));
			connection = DriverManager.getConnection(properties.getProperty("url"),
					properties.getProperty("user"),properties.getProperty("password"));
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
			// 获取结果集的元数据
			ResultSetMetaData rsmd = resultSet.getMetaData();
			//获取总行数
			int columnCount = rsmd.getColumnCount();
			if (resultSet.next()){
				t = cls.newInstance();
				for (int i = 0; i < columnCount; i++) {
					// //1. 获取列的名称
					// String columnName = rsmd.getColumnName(i+1);
					// 1. 获取列的别名
					String columnName = rsmd.getColumnLabel(i + 1);
					// 2. 根据列名获取对应数据表中的数据
					Object columnVal = resultSet.getObject(columnName);
					// 3. 将数据表中得到的数据，封装进对象
					Field field = cls.getDeclaredField(columnName);
					field.setAccessible(true);
					field.set(t, columnVal);
				}
				return t;
			}
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			if (resultSet != null){
				resultSet.close();
			}
			if (statement!=null){
				statement.close();
			}
			if (connection!=null){
				connection.close();
			}
		}
		return null;
	}

}
